package com.zzzy.cont.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhuozhengsoft.pageoffice.OpenModeType;
import com.zzzy.common.exception.BusinessException;
import com.zzzy.common.util.AssertUtil;
import com.zzzy.common.util.FileUtil;
import com.zzzy.common.vo.PageResult;
import com.zzzy.cont.common.enums.ConStatusEnum;
import com.zzzy.framework.common.util.PageOfficeUtil;
import com.zzzy.cont.dao.entity.ConAttachment;
import com.zzzy.cont.dao.entity.Contract;
import com.zzzy.cont.dao.mapper.ConAttachmentMapper;
import com.zzzy.cont.vo.contract.attachment.ConAttachmentAddReq;
import com.zzzy.cont.vo.contract.attachment.ConAttachmentPageReq;
import com.zzzy.cont.vo.pageoffice.OpenOfficeFileRes;
import com.zzzy.framework.common.util.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDateTime;

/**
 * 合同附件 服务实现类
 *
 * @author fc
 * @since 2024-06-11
 */
@Service
public class ConAttachmentService extends ServiceImpl<ConAttachmentMapper, ConAttachment> {

    @Resource
    private ConService conService;
    @Resource
    private ConActivityNoteService conActivityNoteService;

    public PageResult<ConAttachment> getConAttachmentPage(ConAttachmentPageReq queryReq) {
        conService.validateAuthForQuery(queryReq.getConId());

        LambdaQueryWrapper<ConAttachment> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(ConAttachment::getId, ConAttachment::getName, ConAttachment::getCreateTime);

        wrapper.eq(ConAttachment::getConId, queryReq.getConId()).orderByDesc(ConAttachment::getId);
        return baseMapper.selectPage(queryReq, wrapper);
    }

    @Transactional
    public void addConAttachment(ConAttachmentAddReq addReq) {
        Contract contract = conService.getConById(addReq.getConId());
        AssertUtil.isNotEquals(ConStatusEnum.CANCEL.getValue(), contract.getStatus(), "合同状态错误");
        AssertUtil.isEquals(contract.getUserId(), SecurityUtils.getLoginUser().getId(), "当前用户无此操作权限");
        byte[] byteFileBlob;
        try {
            byteFileBlob = addReq.getFile().getBytes();
        } catch (IOException e) {
            throw new BusinessException("文件读取错误");
        }
        ConAttachment conAttachment = new ConAttachment();
        conAttachment.setConId(addReq.getConId());
        conAttachment.setCreateTime(LocalDateTime.now());
        conAttachment.setName(addReq.getFile().getOriginalFilename());
        conAttachment.setFileBlob(byteFileBlob);
        baseMapper.insert(conAttachment);

        conActivityNoteService.addSysNote(addReq.getConId(), "上传附件：" + conAttachment.getName());
    }

    public ConAttachment getSimpleConAttachmentById(Long id) {
        LambdaQueryWrapper<ConAttachment> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(ConAttachment::getId, ConAttachment::getConId, ConAttachment::getName, ConAttachment::getCreateTime);

        wrapper.eq(ConAttachment::getId, id);
        ConAttachment conAttachment = baseMapper.selectOne(wrapper);
        AssertUtil.nonNull(conAttachment, "附件不存在");
        return conAttachment;
    }

    @Transactional
    public void deleteById(Long id) {
        ConAttachment conAttachment = getSimpleConAttachmentById(id);
        Contract contract = conService.getConById(conAttachment.getConId());
        AssertUtil.isNotEquals(ConStatusEnum.CANCEL.getValue(), contract.getStatus(), "合同状态错误");
        AssertUtil.isEquals(contract.getUserId(), SecurityUtils.getLoginUser().getId(), "当前用户无此操作权限");
        baseMapper.deleteById(id);

        conActivityNoteService.addSysNote(conAttachment.getConId(), "删除附件：" + conAttachment.getName());
    }

    public OpenOfficeFileRes getPageOfficeResByConId(Long id, String openFileUrl) {
        ConAttachment conAttachment = getSimpleConAttachmentById(id);
        conService.validateAuthForQuery(conAttachment.getConId());
        String name = conAttachment.getName();
        if (name.endsWith(FileUtil.DOC) || name.endsWith(FileUtil.DOCX)){
            String wordHtml = PageOfficeUtil.getWordHtml(openFileUrl, name, OpenModeType.docReadOnly);
            return OpenOfficeFileRes.builder().html(wordHtml).build();
        } else if (name.endsWith(FileUtil.XLS) || name.endsWith(FileUtil.XLSX)){
            String excelHtml = PageOfficeUtil.getExcelHtml(openFileUrl, name, OpenModeType.xlsReadOnly);
            return OpenOfficeFileRes.builder().html(excelHtml).build();
        } else {
            String pdfHtml = PageOfficeUtil.getPdfHtml(openFileUrl, name);
            return OpenOfficeFileRes.builder().html(pdfHtml).pdf(true).build();
        }
    }

    public ConAttachment getConAttachmentById(Long id) {
        ConAttachment conAttachment = baseMapper.selectById(id);
        AssertUtil.nonNull(conAttachment, "附件不存在");
        conService.validateAuthForQuery(conAttachment.getConId());
        return conAttachment;
    }
}
